from pydantic import BaseModel, EmailStr, Field, field_validator
from datetime import datetime
from typing import Optional, Union
from app.models.user import UserRole

class UserBase(BaseModel):
    """用户基础模型"""
    username: str = Field(..., min_length=3, max_length=50)
    email: Optional[EmailStr] = None
    full_name: Optional[str] = None
    department: Optional[str] = None

class UserCreate(UserBase):
    """用户创建模型"""
    password: str = Field(..., min_length=6, max_length=50)
    role: Optional[UserRole] = UserRole.USER

class UserUpdate(BaseModel):
    """用户更新模型"""
    email: Optional[EmailStr] = None
    full_name: Optional[str] = None
    department: Optional[str] = None
    password: Optional[str] = None
    role: Optional[UserRole] = None
    is_active: Optional[bool] = None

class UserResponse(BaseModel):
    """用户响应模型"""
    id: Union[str, int]  # Support both string and int for backward compatibility
    username: str
    email: Optional[str] = None  # 不使用EmailStr验证，避免前端格式错误
    full_name: Optional[str] = None
    department: Optional[str] = None
    role: UserRole
    avatar_url: Optional[str] = None
    is_active: bool
    created_at: datetime
    
    @field_validator('id', mode='before')
    @classmethod
    def convert_id_to_str(cls, v):
        """Convert id to string for consistency"""
        return str(v) if v is not None else v
    
    class Config:
        from_attributes = True

class Token(BaseModel):
    """令牌响应模型"""
    access_token: str
    token_type: str = "bearer"

class TokenData(BaseModel):
    """令牌数据模型"""
    user_id: Optional[str] = None

